package com.gs.synedocket.util;

import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.gs.synedocket.constant.AllConstants;

import java.util.Locale;

public class LanguageUtils {
    private static volatile LanguageUtils instance;
    private final String LANG_STR_CHINA = "zh-TW,zh";
    private final String LANG_STR_ENGLISH = "en-US,en";
    private final String NAME_ENGLISH = "enName";
    private final String NAME_CHINA = "cnName";
    private Locale currentLocale;
    private String apiLang, dbNameType, mNameType;

    private LanguageUtils() {
    }

    public static LanguageUtils getInstance() {
        if (null == instance) {
            synchronized (LanguageUtils.class) {
                if (instance == null) {
                    instance = new LanguageUtils();
                }
            }
        }
        return instance;
    }

    public Context change(Locale locale) {
        Context context = AppUtil.getInstance().getContext();
        Resources resources = context.getApplicationContext().getResources();
        Configuration config = resources.getConfiguration();
        config.setLocale(locale);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocales(new LocaleList(locale));
            context = context.createConfigurationContext(config);
        } else {
            DisplayMetrics dm = resources.getDisplayMetrics();
            resources.updateConfiguration(config, dm);
        }
        AppUtil.getInstance().initContext(context);
        currentLocale = locale;
        apiLang = locale == Locale.ENGLISH ? LANG_STR_ENGLISH : LANG_STR_CHINA;
        dbNameType = locale == Locale.ENGLISH ? NAME_ENGLISH : NAME_CHINA;
        mNameType = getLanguageInt() == 2 ? "Name" : "ChineseName";
        return context;
    }


    /**
     * 获取当前语言
     *
     * @return
     */
    public Locale getCurrentLanguage() {
        if (currentLocale == null) {
            currentLocale = getLanguageInt() == 2 ? Locale.ENGLISH : Locale.TAIWAN;
        }
        return currentLocale;
    }

    public String getLanguage() {
        if (TextUtils.isEmpty(apiLang)) {
            apiLang = getLanguageInt() == 2 ? LANG_STR_ENGLISH : LANG_STR_CHINA;
        }
        return apiLang;
    }

    public int getLanguageInt() {
        return SPUtil.getInstance().getInt(AllConstants.LANGUAGE, 1);
    }


    public String getNameFromLan() {
        if (TextUtils.isEmpty(dbNameType)) {
            dbNameType = getLanguageInt() == 2 ? NAME_ENGLISH : NAME_CHINA;
        }
        return dbNameType;
    }

    public String getNameFromLan(String type) {
        if (TextUtils.isEmpty(mNameType)) {
            mNameType = getLanguageInt() == 2 ? "Name" : "ChineseName";
        }
        return type + mNameType;
    }
}
